//
//  HomeViewController.m
//  StockNet
//
//  Created by 小焘无量 on 2023/1/5.
//

#import "HomeViewController.h"
#import "StockInfoTableViewCell.h"

@interface HomeViewController ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *allPageLab;
@property (weak, nonatomic) IBOutlet UILabel *currentPageLab;



@property (weak, nonatomic) IBOutlet UIButton *upPageBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *downBtnLeftLayout;// 10 70
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *currentPageLabLeftLayout;//70 130


@property (weak, nonatomic) IBOutlet UIButton *downPageBtn;
@property (weak, nonatomic) IBOutlet UIButton *searchBtn;

@property (weak, nonatomic) IBOutlet UITextField *searchNameTF;
@property (weak, nonatomic) IBOutlet UITextField *searchSpecTF;
@property (weak, nonatomic) IBOutlet UITextField *searchMaterialTF;


@property (nonatomic, strong) NSMutableArray *modelArr;


@end

@implementation HomeViewController

#pragma mark - LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:NotifiName_LoginStateChange object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:NotifiName_MemberStateChange object:nil];
    
    [self UIConfig];
    
    [self getListNetworkIsMore:NO showLoading:NO];
}

-(void)dealloc {
    //[[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - view layout
- (void)UIConfig {
    
    self.view.backgroundColor = kRGB(0xFAFAFA);
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:StockInfoTableViewCellID bundle:nil] forCellReuseIdentifier:StockInfoTableViewCellID];
    //    self.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.01)];
    //    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.01)];
    
    self.searchNameTF.delegate = self;
    self.searchSpecTF.delegate = self;
    self.searchMaterialTF.delegate = self;
    
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    
    [self btnColorConfig];
    
}

-(void)btnColorConfig {
    [self.upPageBtn setTitleColor:kThemeColor forState:UIControlStateNormal];
    [self.downPageBtn setTitleColor:kThemeColor forState:UIControlStateNormal];
    self.searchBtn.backgroundColor = kThemeColor;
}

#pragma mark - Event Response

//通知消息
-(void)notificationAction:(NSNotification *)info {
    if ([info.name isEqualToString:NotifiName_LoginStateChange] || [info.name isEqualToString:NotifiName_MemberStateChange]) {
        self.pageNum = 1;
        [self getListNetworkIsMore:NO showLoading:YES];
    }
}

- (IBAction)upPageAction:(id)sender {
    self.pageNum--;
    [self getListNetworkIsMore:YES showLoading:YES];
}

- (IBAction)downPageAction:(id)sender {
    self.pageNum++;
    [self getListNetworkIsMore:YES showLoading:YES];
}

// 搜索
- (IBAction)searchBtnAction:(id)sender {
//    spec  // 规格
//    textureMaterial // 材质
//    varieties  名称
    
    self.pageNum = 1;
    [self getListNetworkIsMore:NO showLoading:YES];
    
}


#pragma mark - Delegate,DataSource
#pragma mark  UITableViewDataSource,UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.modelArr.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    StockInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:StockInfoTableViewCellID forIndexPath:indexPath];
    cell.model = self.modelArr[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [self getListNetworkIsMore:NO showLoading:YES];
    [self.view endEditing:YES];
    return YES;
}

#pragma mark  DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//是否允许点击（默认是YES）
- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView{
   return NO;
}

//空白区域点击事件
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view{
   
}
//返回标题文字
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView{
    
    NSString *title = @"暂无信息";
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor colorWithHexString:@"575757"]};
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

#pragma mark - Network
-(void)getListNetworkIsMore:(BOOL)isMore showLoading:(BOOL)showLoading{
    
    self.pageNum = !self.pageNum ? 1 : self.pageNum;
    
    NSMutableDictionary *dic = [NSMutableDictionary new];
    //名称
    if ([self.searchNameTF.text isNotBlank]) {
        [dic setObject:self.searchNameTF.text forKey:@"varieties"];
    }
    
    // 规格
    if ([self.searchSpecTF.text isNotBlank]) {
        [dic setObject:self.searchSpecTF.text forKey:@"spec"];
    }
    
    // 材质
    if ([self.searchMaterialTF.text isNotBlank]) {
        [dic setObject:self.searchMaterialTF.text forKey:@"textureMaterial"];
    }
    
    [dic setObject:FormatString(@"%ld", self.pageNum) forKey:@"current"];
    [dic setObject:NETPageSize forKey:@"size"];
    
    WeakSelf;
    
    if (showLoading) {
        [MBProgressHUD showLoadingMessage:nil view:self.view];
    }
    
    [[APIManager manager] Get:URL_InstockList parameters:dic success:^(id  _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view];
        
//        if (NET_RESULT_CODE == 200) {
//
//            NSArray *arr = responseObject[@"data"][@"records"];
//            NSMutableArray *modelArr = [[NSMutableArray alloc]init];
//            for (NSDictionary *dic in arr) {
//                InstockListModel *model = [InstockListModel mj_objectWithKeyValues:dic];
//                [modelArr addObject:model];
//            }
//            if (isMore) {
//                [weakSelf.modelArr addObjectsFromArray:modelArr];
//            }else {
//                weakSelf.modelArr = [NSMutableArray arrayWithArray:modelArr];
//            }
//
//            weakSelf.pageNum++;
//            [weakSelf.tableView reloadData];
//            [weakSelf.tableView endRefreshing];
//
//            NSInteger total = [responseObject[@"data"][@"total"] integerValue];
//            if (weakSelf.modelArr.count < total) {
//                [weakSelf.tableView updateFooterWithEnd:NO];
//            }else {
//                [weakSelf.tableView updateFooterWithEnd:YES];
//            }
//
//        }else {
//            NET_SHOW_MSG;
//            [weakSelf.tableView endRefreshing];
//        }
        
        if (NET_RESULT_CODE == 200) {
            [weakSelf dealUIWithData:responseObject];
        } else {
            NET_SHOW_MSG;
        }
        
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:weakSelf.view];
        NET_SHOW_ERROR;
        [weakSelf.tableView endRefreshing];
    }];
}

// 心跳接口


#pragma mark - Method
-(void)dealUIWithData:(id)responseObject {
    
    NSInteger allPages = [responseObject[@"data"][@"pages"] integerValue];
    NSInteger currentPage = [responseObject[@"data"][@"current"] integerValue];
    NSInteger totalCount = [responseObject[@"data"][@"total"] integerValue];
    
//    @property (weak, nonatomic) IBOutlet NSLayoutConstraint *downBtnLeftLayout;// 10 70
//    @property (weak, nonatomic) IBOutlet NSLayoutConstraint *currentPageLabLeftLayout;//70 130
    
    if (currentPage == allPages) {
        // 没有下一页
        self.downPageBtn.hidden = YES;
        self.upPageBtn.hidden = NO;
//        self.currentPageLabLeftLayout.constant = 70;
    } else if(currentPage == 1){
        // 没有上一页
        self.upPageBtn.hidden = YES;
        self.downPageBtn.hidden = NO;
//        self.downBtnLeftLayout.constant = 10;
//        self.currentPageLabLeftLayout.constant = 70;
    }else {
        // 有上一页 也有下一页
        self.upPageBtn.hidden = NO;
        self.downPageBtn.hidden = NO;
//        self.downBtnLeftLayout.constant = 70;
//        self.currentPageLabLeftLayout.constant = 130;
    }
    
    self.allPageLab.text = FormatString(@"共%ld页 %ld条记录", allPages, totalCount);
    self.currentPageLab.text = FormatString(@"当前第%ld页", currentPage);
    
    NSArray *arr = responseObject[@"data"][@"records"];
    NSMutableArray *modelArr = [[NSMutableArray alloc]init];
    for (NSDictionary *dic in arr) {
        InstockListModel *model = [InstockListModel mj_objectWithKeyValues:dic];
        [modelArr addObject:model];
    }
    
    if(modelArr.count == 0) {
        // 有上一页 也有下一页
        self.upPageBtn.hidden =
        self.downPageBtn.hidden = YES;
//        self.currentPageLabLeftLayout.constant = 10;
    }
    
    self.modelArr = [NSMutableArray arrayWithArray:modelArr];
    
    [self.tableView reloadData];
}

//// 搜索方法
//- (void)searchMethodAction {
//
//    NSMutableDictionary *dic = [NSMutableDictionary new];
//
//    //名称
//    if ([self.searchNameTF.text isNotBlank]) {
//        [dic setObject:self.searchNameTF.text forKey:@"varieties"];
//    }
//
//    // 规格
//    if ([self.searchSpecTF.text isNotBlank]) {
//        [dic setObject:self.searchSpecTF.text forKey:@"spec"];
//    }
//
//    // 材质
//    if ([self.searchMaterialTF.text isNotBlank]) {
//        [dic setObject:self.searchMaterialTF.text forKey:@"textureMaterial"];
//    }
//
//    self.pageNum = 1;
//    [self getListNetworkIsMore:NO dic:dic showLoading:YES];
//}

#pragma mark - Set Get

#pragma mark - Lazy

@end
